package com.tsd.core.utils;

import com.google.zxing.WriterException;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zsy
 */
public class WaterMarkUtils {

    public static BufferedImage createQrCodeImg(String data) throws WriterException {
        // 生成二维码
        return QrCodeUtils.createQrCodeBufferdImage(data, 300, 300);
    }

    /**
     * PDF附件添加二维码
     *
     * @param bos   输出文件的位置
     * @param input 输入文件流
     * @author nicky.ma
     * @date 2019年6月11日下午3:42:15
     */
    public static void setQrCodeForPDF(BufferedOutputStream bos, InputStream input, Double positionX, Double positionY) throws IOException, DocumentException, WriterException {
        BufferedImage bufferedImage = createQrCodeImg(null);
        //PDF附件加上二维码水印
        setWatermarkForPDF(bos, input, bufferedImage, positionX, positionY, "field");
    }

    /**
     * A4的宽高（mm）
     */
    final static int A4_WIDTH = 210;
    final static int A4_HEIGHT = 297;
    /**
     * 二维码的大小（长宽像素）
     */
    final static int QR_WIDTH = 30;
    final static int QR_HEIGHT = 30;
    final static Double QR_ZOOM = 1.1;

    /**
     * 为PDF附件添加图片水印
     *
     * @param bos   输出文件的位置
     * @param input 输入文件流
     * @param image 水印图片
     * @author nicky.ma
     * @date 2019/6/11 12:00:32
     */
    public static void setWatermarkForPDF(BufferedOutputStream bos, InputStream input, BufferedImage image, Double positionX, Double positionY, String field_sid)
            throws IOException, DocumentException {
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, bos);
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte waterMar;
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            Rectangle pageSize = reader.getPageSize(i);
            //以mm计算的宽度、高度,正常A4竖向时，width:210mm,height:297mm
            double width = (pageSize.getWidth() > pageSize.getHeight() ? pageSize.getHeight() : pageSize.getWidth()) * 25.4 / 72;
            double height = (pageSize.getWidth() > pageSize.getHeight() ? pageSize.getWidth() : pageSize.getHeight()) * 25.4 / 72;
            double ratio = Math.max(width / A4_WIDTH, height / A4_HEIGHT);
            //content = stamper.getOverContent(i);// 在内容上方加水印
//            waterMar = stamper.getUnderContent(1);//在内容下方加水印
            waterMar = stamper.getOverContent(i);
            // 设置图片透明度为0.2f
            //gs.setFillOpacity(0.2f);
            // 设置笔触字体不透明度为0.4f
            //gs.setStrokeOpacity(0.4f);
            // 开始水印处理
            waterMar.beginText();
            // 设置透明度
            waterMar.setGState(gs);
            // 设置水印字体参数及大小
            //waterMar.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED), 60);
            // 设置水印对齐方式 水印内容 X坐标 Y坐标 旋转角度
            //waterMar.showTextAligned(Element.ALIGN_CENTER, "公司内部文件，请注意保密！",  500, 430, 45);
            // 设置水印颜色
            //waterMar.setColorFill(BaseColor.GRAY);
            // 创建水印图片
            Image itextimage = getImage(image);
            // 水印图片位置
            float llx = (float) (positionX.floatValue() * ratio);
            float lly = (float) (positionY.floatValue() * ratio);
            itextimage.setAbsolutePosition((float) (positionX.floatValue() * ratio), (float) (positionY.floatValue() * ratio));
            // 边框固定
//            itextimage.scaleToFit(200, 200);
            // 设置旋转弧度
            //image.setRotation(30);// 旋转 弧度
            // 设置旋转角度
            //image.setRotationDegrees(45);// 旋转 角度
            // 设置等比缩放
            //itextimage.scalePercent(90);
            // 自定义大小
            int qr_wid = (int) (Math.round(QR_WIDTH * ratio) * QR_ZOOM);
            itextimage.scaleAbsolute(qr_wid, qr_wid);
            float urx = llx + qr_wid;
            float ury = lly + qr_wid;
//            System.out.println("图片尺寸width="+width+"==height=="+height+"==ratio=="+ratio+"==qr_wid=="+qr_wid);
            // 附件加上水印图片
//            waterMar.addImage(itextimage);
            // 完成水印添加
            waterMar.endText();
            // stroke
            waterMar.stroke();
            Rectangle box = new Rectangle(llx, lly, urx, ury);
            PushbuttonField fld = new PushbuttonField(stamper.getWriter(), box, "myimage" + field_sid + i);
            fld.setLayout(PushbuttonField.LAYOUT_ICON_ONLY);
            fld.setImage(itextimage);
            stamper.addAnnotation(fld.getField(), i);
        }
        stamper.close();
        reader.close();
    }

    private static Image getImage(BufferedImage image) throws IOException, BadElementException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", out);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] byteArray = out.toByteArray();
        Image iTextImage = Image.getInstance(byteArray);
        return iTextImage;
    }
}
